#!/bin/bash
set -ex

cd $(dirname $0)/..
. ./hack/version.sh

RUNC_DIR=build/src/github.com/opencontainers/runc
CONTAINERD_DIR=build/src/github.com/containerd/containerd
HCSSHIM_DIR=build/src/github.com/microsoft/hcsshim
DATA_DIR=build/data
CHARTS_DIR=build/static/charts
NERDCTL_VERSION=2.0.0
CILIUMCLI_VERSION=v0.16.20

umask 022
rm -rf ${CHARTS_DIR}
rm -rf ${RUNC_DIR}
rm -rf ${CONTAINERD_DIR}
rm -rf ${HCSSHIM_DIR}
mkdir -p ${DATA_DIR}
mkdir -p ${CHARTS_DIR}
mkdir -p bin

case ${OS} in
  linux)
     git clone --single-branch --branch=${VERSION_RUNC} --depth=1 https://github.com/k3s-io/runc ${RUNC_DIR}
    ;;
  windows)
    git clone --single-branch --branch=${VERSION_HCSSHIM} --depth=1 https://github.com/microsoft/hcsshim ${HCSSHIM_DIR}
    ;;
  *)
    echo "[ERROR] unrecognized opertaing system: ${OS}"
    exit 1
    ;;
esac

git clone --single-branch --branch=${VERSION_CONTAINERD} --depth=1 https://${PKG_CONTAINERD_K8E} ${CONTAINERD_DIR}

download_and_package_nerdctl() {
echo "download nerdctl..."
if [ ${ARCH} = amd64 ]; then
  curl --compressed -sfL https://github.com/containerd/nerdctl/releases/download/v${NERDCTL_VERSION}/nerdctl-${NERDCTL_VERSION}-linux-amd64.tar.gz | tar -zxf - -C bin
elif [ ${ARCH} = aarch64 ] || [ ${ARCH} = arm64 ]; then
  curl --compressed -sfL https://github.com/containerd/nerdctl/releases/download/v${NERDCTL_VERSION}/nerdctl-${NERDCTL_VERSION}-linux-arm64.tar.gz | tar -zxf - -C bin
fi
}

download_and_package_cilium() {
  echo "download Cilium-cli..."
  if [ ${ARCH} = amd64 ]; then
    curl --compressed -sfL https://github.com/cilium/cilium-cli/releases/download/${CILIUMCLI_VERSION}/cilium-linux-amd64.tar.gz | tar -zxf - -C bin
  elif [ ${ARCH} = aarch64 ] || [ ${ARCH} = arm64 ]; then
    curl --compressed -sfL https://github.com/cilium/cilium-cli/releases/download/${CILIUMCLI_VERSION}/cilium-linux-arm64.tar.gz | tar -zxf - -C bin
  fi
}

download_and_package_nerdctl
download_and_package_cilium
